import $store from '@/store/index.js'
let needLoadingNumber =0
export default {
	// 全局配置
	common: {
		baseUrl: getApp().globalData.baseUrl,
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
		},
		data: {},
		method: 'GET',
		dataType: 'json',
		whiteList: ['pagesPackage/minePackage/login/login','pagesPackage/minePackage/register/index','pagesPackage/minePackage/forgotPassword/index']
	},
	startLoading() {
	    uni.showLoading({
	    	title: '加载中...',
			mask: true
	    });
	},
	closeLoading(){
	    setTimeout(()=>{
	        uni.hideLoading()
	    },500)
	},
	showFullLoading(){
	    if(needLoadingNumber === 0){
	        this.startLoading()
	    } 
	    needLoadingNumber ++
	},
	closeFullLoading(){
	    if(needLoadingNumber <= 0) return 
	    needLoadingNumber --
	    if(needLoadingNumber === 0) {
	        this.closeLoading()
	    }
	},
	// 请求 返回promise
	request(options = {}) {
		this.showFullLoading()
		// 组织参数
		options.url = this.common.baseUrl + options.url
		options.header = options.header || this.common.header
		options.data = options.data || this.common.data
		options.method = options.method || this.common.method
		options.dataType = options.dataType || this.common.dataType
		
		// 获取当前页面实例
		const pages = getCurrentPages();
		// 获取当前页面的实例
		const currentPage = pages[pages.length - 1];
		// 获取页面url
		const url = currentPage.route;
		// token
		let token = uni.getStorageSync('USER_ID') || $store.state.user.token
		if(!token){
			if (this.common.whiteList.indexOf(url) !== -1 ) {
				// 二次验证
				// 登录与注册不需要验证TOKEN
				
				
			}else {
				uni.showToast({
					title: '请先登录',
					icon: 'none',
					success() {
						return uni.navigateTo({
							url: '/pagesPackage/minePackage/login/login',
						});
					}
				});
			}
		}
		

		// 请求
		return new Promise((res, rej) => {
			// 请求之前... todo
			// 请求中...
			uni.request({
				...options,
				success: (result) => {
					// 返回原始数据
					if (options.native) {
						return res(result)
					}
					// 服务端失败
					if (result.statusCode !== 200) {
						if (options.toast !== false) {
							uni.showToast({
								title: result.data.msg || '服务端失败',
								icon: 'none'
							});
						}
						return rej(result.data)
					}
					// 成功
					this.closeFullLoading()
					let data = result.data
					res(data)
				},
				fail: (error) => {
					this.closeFullLoading()
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					return rej()
				}
			});
		})
	},
	// get请求
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// delete请求
	del(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
}